﻿/*--------------------------------------------------------------
 * <copyright file="OPRolesQueryControlNew.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Li Dawei Zhang Jun</author>
 * <summary>
 *     *** OP 权限 查询 ***
 *     引用服务：WCFServers.OthersQueryRef
 *     服务功能：OP权限数据查询
 *   
 *     引用服务：WCFLog4Ref.WCFLog4Client
 *     服务功能：记录日志
 *
 *      作成日：10/09/2010
 *              由OPRolesQueryControl-Hide改名形成的页面。
 *              原页面的功能基本保留。但，
 *              将原来数据导出用的DATAGRID变为当前可视操作的数据源数据。
 *              10/12/2010 Add 后台动态设置内容变色
 *              10/14/2010 修改 导出功能异常
 *              10/18/2010 修改 点击标题头排序时，导出内容不是排序结果的问题。
 *              12/24/2010 增加 F和G 对应字段
 *              05/06/2011 修改 统计权限数放到BackgroundWorker线程内
 * <summary>
 *--------------------------------------------------------------
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.TheOthersRelated.OPRolesQuery
{
    using System;
    using System.Collections.ObjectModel;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.OthersQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;
    using System.Windows.Threading;
    using System.ComponentModel;

    public partial class OPRolesQueryControlNew : UserControl
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " OP权限查询";

        /// <summary>
        /// 查询子窗体 opidSelect
        /// </summary>
        private childWindow.OPIDSelectChildWindow opidSelect = null;

        /// <summary>
        /// 查询子窗体 lineSelectWin
        /// </summary>
        childWindow.LineSelChildWin lineSelect = null;

        /// <summary>
        /// 消息子窗体 errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox = null;

        /// <summary>
        /// 日志服务定义
        /// wcfLogClient
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient = null;

        /// <summary>
        /// OP 权限查询
        /// </summary>
        private WCFTheOthersQueryClient wcfOthersQueryClient = null;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 用户选择条件日志
        /// </summary>
        string whereInforLogs;

        /// <summary>
        /// 记录要导出的数据
        /// </summary>
        DataGrid DataToCSV;

        /// <summary>
        /// 统计 所有权限中O的数量
        /// 07/28/2010 -- Add
        /// </summary>
        private int totalPersons = 0;
        private int totalAB_Japan = 0;
        private int totalD_Japan = 0;
        private int totalE_Japan = 0;

        private int totalAB_English = 0;
        private int totalD_English = 0;
        private int totalE_English = 0;
        private int totalDistinguish = 0;
        private int totalTrimer = 0;

        // 08/13/2010 -- add 
        private int totalA_English = 0;
        private int totalA_Japan = 0;
        private int totalA_Chinese = 0;
        private int totalAB_Chinese = 0;
        private int totalD_Chinese = 0;
        private int totalE_Chinese = 0;

        //12/24/2010 增加 F和G 对应字段
        private int totalF_English = 0;
        private int totalG_English = 0;
        private int totalF_Japan = 0;
        private int totalG_Japan = 0;
        private int totalF_Chinese = 0;
        private int totalG_Chinese = 0;

        /// <summary>
        /// 记录总数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private int sumRecordCount = 0;

        /// <summary>
        /// 记录NumericUpDown分页数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private double oldNumericUpDown = 0;

        /// <summary>
        ///  记录返回结果，统计数据用
        /// </summary>
        /// <value> 05/06/2011 add </value>
        static ObservableCollection<OperatorRolesData> eResult;

        #endregion 全局变量

        public OPRolesQueryControlNew()
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme(this);
            //Accordion 时的Border 控件 引用主题
            ((App)Application.Current).SetTheme(bAccordionItemBorder);

            this.InitField();

            this.dgOPRolesDataListExport.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            //查询按钮
            this.btnSelList.Click += new RoutedEventHandler(btnSelList_Click);

            //... 按钮
            this.btnSelContext.Click += new RoutedEventHandler(btnSelContext_Click);

            // OPID 子窗体关闭 
            this.opidSelect.Closed += new EventHandler(opidSelect_Closed);

            // LINE子窗体关闭
            this.lineSelect.Closed += new EventHandler(lineSelect_Closed);

            //OP 权限查询 委托
            this.wcfOthersQueryClient.SelectOperatorRolesQueryInforCompleted +=
                        new EventHandler<SelectOperatorRolesQueryInforCompletedEventArgs>(wcfOthersQueryClient_SelectOperatorRolesQueryInforCompleted);

            //数据 导出（只有SSV或SQC可用此功能）
            this.btnExport.Click += new RoutedEventHandler(btnExport_Click);

            //页面载入
            this.Loaded += new RoutedEventHandler(OPRolesQueryControlNew_Loaded);

            //查询按钮可用
            this.btnSelList.IsEnabled = true;

            //LoadingRow事件 10/12/2010 Add （变色用）
            this.dgOPRolesDataListExport.LoadingRow += new EventHandler<DataGridRowEventArgs>(dgOPRolesDataListExport_LoadingRow);
            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));

        }

        #region 页面载入
        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void OPRolesQueryControlNew_Loaded(object sender, RoutedEventArgs e)
        {
            // 只有SSV或SQC可用使用 数据导出 功能
            // (如果当前用户不是 SV或QC 显示 数据导出 功能)
            if (!(ClientUserInfor.RoleName.ToUpper().Trim().Equals("SV") || ClientUserInfor.RoleName.ToUpper().Trim().Equals("QC")))
            {
                this.btnExport.Visibility = Visibility.Visible;
            }

            //设置 初始统计值 
            ClearOrSetTotalValue(true, 0);
            this.nuPageSize.IsEnabled = true;//分页数控制
        }
        #endregion 页面载入

        #region 变量初始化方法  InitField
        /// <summary>
        /// 变量初始化方法  InitField
        /// </summary>
        private void InitField()
        {
            this.opidSelect = new childWindow.OPIDSelectChildWindow();
            this.lineSelect = new childWindow.LineSelChildWin();
            this.errorMessbox = new childWindow.MessageBox();
            this.wcfLogClient = Wcf.Service.Log4;
            this.wcfOthersQueryClient = Wcf.Service.TheOthersQuery;
            this.whereInforLogs = string.Empty;
        }
        #endregion 变量初始化方法  InitField

        #region 按 ... 按钮 显示相应 子窗体
        /// <summary>
        /// ... 按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSelContext_Click(object sender, RoutedEventArgs e)
        {

            if (this.domainUpDownSel.CurrentIndex >= 0)
            {
                switch (this.domainUpDownSel.CurrentIndex)
                {
                    //按OP的ID号 查询
                    case 0:
                        OPIDChildWin_Show();
                        break;

                    //按线路 查询
                    case 1:
                        LineChildWin_Show();
                        break;
                }
            }
        }

        /// <summary>
        /// 显示 OP 查询子窗体
        /// </summary>
        void OPIDChildWin_Show()
        {
            this.opidSelect.Title = "查询子窗体";
            this.opidSelect.Show();
        }

        /// <summary>
        /// 显示 线路查询子窗体
        /// </summary>
        void LineChildWin_Show()
        {
            this.lineSelect.Title = "线路查询子窗体";
            this.lineSelect.Show();

        }

        #endregion 按 ... 按钮 显示相应 子窗体

        #region 子窗体关闭
        /// <summary>
        /// LINE 子窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void lineSelect_Closed(object sender, EventArgs e)
        {
            try
            {
                //this.lineSelectWin = (childWindow.LineSelChildWin)sender;
                this.lineSelect = sender as childWindow.LineSelChildWin;

                if (this.lineSelect == null) { return; }

                if (this.lineSelect.DialogResult == true)
                {
                    //将LINE记录值添加逗号(多值时)
                    // ClientDataList.SelOpIDList
                    if (ClientDataList.SelLineList.Count > 0)
                    {
                        #region 多值时,添加逗号
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in ClientDataList.SelLineList)
                        {
                            sb.Append(str + ",");
                        }

                        this.tbSelLineContext.Text = string.Empty;

                        // 去除尾部多余逗号
                        this.tbSelLineContext.Text = sb.ToString().Remove(sb.ToString().Length - 1, 1);
                        ClientDataList.SelOpIDList.Clear();
                        #endregion 多值时,添加逗号

                        this.tbSelLineContext.Text = string.Empty;
                        this.tbSelLineContext.Text = this.lineSelect.retRadioButtonContent.ToString();

                        return;
                    }
                    //取消所有选择时或是没有选择时，清空文本
                    else
                    {
                        this.tbSelLineContext.Text = string.Empty;
                    }

                }

                if (this.lineSelect.DialogResult == false)
                {
                    ClientDataList.SelLineList.Clear();
                    ClientDataList.CheckOpUnitList.Clear();
                    return;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                            " lineSelectWin_Closed 转换Line信息时出错" +
                                            ex.Message.ToString() +
                                            this.whereInforLogs);

                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        ///  OPID 子窗体关闭 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void opidSelect_Closed(object sender, EventArgs e)
        {
            try
            {
                this.tbSelOPUnitContext.Text = string.Empty;
                tbSelOPUnitContext.Tag = string.Empty;

                //this.opidSelect = (Common.Window.OPIDSelectChildWindow)sender;
                this.opidSelect = sender as Common.Window.OPIDSelectChildWindow;
                if (this.opidSelect.DialogResult == true)
                {
                    // 选择部分OP
                    // 添加逗号
                    // ClientDataList.SelOpIDList
                    if (ClientDataList.SelOpIDList.Count > 0)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (string str in ClientDataList.SelOpIDList)
                        {
                            sb.Append(str + ",");
                        }

                        // 去除尾部多余逗号
                        this.tbSelOPUnitContext.Text = sb.ToString().Remove(sb.ToString().Length - 1, 1);
                        ClientDataList.SelOpIDList.Clear();
                        return;
                    }

                    // 选择所有OP//选择部分UNIT时，记录UNIT号
                    // ClientDataList.CheckOpUnitList 一旦有值，不能清空
                    if (ClientDataList.CheckOpUnitList.Count > 0)
                    {

                        tbSelOPUnitContext.Tag = "ALL";

                        //选择所有OP
                        if (this.opidSelect.SelectStatus.ToUpper().Contains("OPERATORS"))
                        {
                            tbSelOPUnitContext.Text = this.opidSelect.SelectStatus;
                        }

                        //选择组
                        if (this.opidSelect.SelectStatus.ToUpper().Contains("UNIT"))
                        {
                            StringBuilder sbUnit = new StringBuilder();
                            foreach (string unitName in ClientDataList.CheckOpUnitList)
                            {
                                sbUnit.Append(unitName);
                                sbUnit.Append("Unit");
                                sbUnit.Append(" ");
                            }
                            tbSelOPUnitContext.Text = sbUnit.ToString();
                        }

                        return;
                    }
                }

                if (this.opidSelect.DialogResult == false)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                ctrlName + 
                                                "转换OPID时出错" +
                                                ex.Message.ToString() +
                                                this.whereInforLogs);

                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }

        }
        #endregion 子窗体关闭

        #region 查询相关
        /// <summary>
        /// 查 询 按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSelList_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                this.whereInforLogs = "查询信息： OP信息：" +
                                        this.tbSelOPUnitContext.Text +
                                        "线路信息：" +
                                        this.tbSelLineContext.Text;

                // 条件约束
                if (string.IsNullOrEmpty(this.tbSelLineContext.Text) || string.IsNullOrEmpty(this.tbSelOPUnitContext.Text))
                {
                    Common.FunctionList.FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      1,
                      "提示",
                      "查询内容不能为空。",
                      Colors.Gray,
                      true,
                      Visibility.Visible,
                      Visibility.Collapsed);

                    return;
                }

                // 传送到服务端的参数列表
                ObservableCollection<WCFServers.OthersQueryRef.WhereParameters> clientWhereList = new ObservableCollection<WCFServers.OthersQueryRef.WhereParameters>();
                WCFServers.OthersQueryRef.WhereParameters fitWhereData = new WhereParameters();

                //---------条件组合---Start-----------------
                ///09/21/2010 修改 OP权限查询框由一个变为两个
                ///所以条件组合，取消switch语句
                ///
                // 判断是ALL还是部分OPID
                if (this.tbSelOPUnitContext.Tag.ToString().Contains("ALL"))
                {
                    // 选择所有组OP或是UNIT
                    StringBuilder sb = new StringBuilder();

                    if (ClientDataList.CheckOpUnitList.Count > 0)
                    {
                        foreach (string s in ClientDataList.CheckOpUnitList)
                        {
                            // 添加逗号
                            sb.Append(s + ",");
                        }

                        // 去除尾部多余逗号
                        fitWhereData.WhereUnit = sb.ToString().Remove(sb.ToString().Length - 1, 1);
                    }

                    fitWhereData.WhereOpID = null;
                }
                else
                {
                    // 选择部分OP
                    // 已加完逗号，不用再转换
                    fitWhereData.WhereOpID = FunctionClass.MyIsNullOrEmpty(this.tbSelOPUnitContext.Text.Trim().ToString(), null);
                }


                // 如果选 LINE 方式查询
                if (ClientDataList.SelLineList.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (string s in ClientDataList.SelLineList)
                    {
                        // 添加逗号
                        sb.Append(s + ",");
                    }

                    // 去除尾部多余逗号
                    fitWhereData.WhereServer = sb.ToString().Remove(sb.ToString().Length - 1, 1);
                }

                //---------条件组合---End-------------------

                clientWhereList.Add(fitWhereData);

                SetBusyBar(1000);

                //调用 OP 权限查询 
                this.wcfOthersQueryClient.SelectOperatorRolesQueryInforAsync(clientWhereList);

                //查询按钮不可用
                this.btnSelList.IsEnabled = false;
                this.nuPageSize.IsEnabled = false;//分页数控制

                clientWhereList.Clear();
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                                ctrlName + 
                                                                ex.Message.ToString() +
                                                                this.whereInforLogs);

                this.nuPageSize.IsEnabled = true;//分页数控制
                //查询按钮可用
                this.btnSelList.IsEnabled = true;

                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// OP 权限查询 实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <value>08/13/2010 增加中国语权限 和 英数日语A权限 对应统计信息。</value>
        void wcfOthersQueryClient_SelectOperatorRolesQueryInforCompleted(object sender, SelectOperatorRolesQueryInforCompletedEventArgs e)
        {
            try
            {
                //查询按钮可用
                this.btnSelList.IsEnabled = true;
                this.nuPageSize.IsEnabled = true;//分页数控制

                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        //记录所查询的记录总数
                        this.sumRecordCount = e.Result.Count;

                        //查询按钮可用
                        this.btnSelList.IsEnabled = true;
                        this.nuPageSize.IsEnabled = true;//分页数控制


                        this.pcv = new PagedCollectionView(e.Result);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        this.dgOPRolesDataListExport.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        //为导出数据
                        DataToCSV = new DataGrid();
                        DataToCSV.ItemsSource = e.Result;

                        // 为统计权限数据 保留e.Result数据源
                        eResult = null;
                        eResult = e.Result;

                        ClearOrSetTotalValue(true, 0);

                        Dispatcher.BeginInvoke(() => DataContext = false);

                        #region BackgroundWorker 线程 统计权限数据 05/06/2011 ADD

                        ///BackgroundWorker会在主线程之外，另开一个后台线程
                        ///，我们可以把一些处理放在后台线程中处理，完成之后，
                        ///后台线程会把结果传递给主线程，同时结束自己。
                        BackgroundWorker totalThread = new BackgroundWorker();
                        
                        totalThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(totalThread_RunWorkerCompleted);
                        totalThread.DoWork += new DoWorkEventHandler(totalThread_DoWork);
                        totalThread.RunWorkerAsync();

                        #endregion BackgroundWorker 线程 统计权限数据

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    "在 OP录入权限查询 中查询记录" +
                                                    this.whereInforLogs);
                    }
                    else
                    {
                        this.dgOPRolesDataListExport.ItemsSource = null;
                        this.dpDataPage.DataContext = null;

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr + 
                                                "在 OP录入权限查询 中没有查询到记录" +
                                                this.whereInforLogs);

                        throw new Exception("录入权限查询 查询中没有可显示的OP数据");
                    }
                }
                else
                {
                    throw new Exception("SelectOperatorRolesQueryInforCompleted服务返回值有错" + e.Error.Message.ToString());
                }
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() => DataContext = false);

                //清空 统计值 
                ClearOrSetTotalValue(true, 0);

                this.nuPageSize.IsEnabled = true;//分页数控制

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                    ctrlName + 
                                                    ex.Message.ToString()+
                                                    this.whereInforLogs);

                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #region 统计权限数据

        /// <summary>
        /// 当线程起动时，统计数据
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void totalThread_DoWork(object sender, DoWorkEventArgs e)
        {
            SetTotlaCount();

            ///这里只是简单的把参数当做结果返回，
            ///当然也可以在这里做复杂的处理后，
            ///再返回自己想要的结果(这里的操作是在另一个线程上完成的) 
            e.Result = e.Argument;
        }

        /// <summary>
        /// 当统计完毕时，需要处理的事件
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        void totalThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //这时后台线程已经完成，并返回了主线程，所以可以直接使用UI控件了 
            ClearOrSetTotalValue(false, 0);
        }

        /// <summary>
        /// 统计 所有权限中O的数量 
        /// </summary>
        public void SetTotlaCount() 
        {
            #region 统计 所有权限中O的数量 

            foreach (object o in eResult)
            {
                WCFServers.OthersQueryRef.OperatorRolesData item = o as WCFServers.OthersQueryRef.OperatorRolesData;

                //Distinguish
                if (item.Distinguish.Contains("O") || item.Distinguish.Contains("Ｏ"))
                {
                    totalDistinguish += 1;
                }

                //Trimer
                if (item.Trimer.Contains("O") || item.Trimer.Contains("Ｏ"))
                {
                    totalTrimer += 1;
                }

                //AB_Japan
                if (item.AB_Japan.Contains("O") || item.AB_Japan.Contains("Ｏ"))
                {
                    totalAB_Japan += 1;
                }

                //D_Japan
                if (item.D_Japan.Contains("O") || item.D_Japan.Contains("Ｏ"))
                {
                    totalD_Japan += 1;
                }

                //E_Japan
                if (item.E_Japan.Contains("O") || item.E_Japan.Contains("Ｏ"))
                {
                    totalE_Japan += 1;
                }

                //AB_English
                if (item.AB_English.Contains("O") || item.AB_English.Contains("Ｏ"))
                {
                    totalAB_English += 1;
                }

                //D_English
                if (item.D_English.Contains("O") || item.D_English.Contains("Ｏ"))
                {
                    totalD_English += 1;
                }

                //E_English
                if (item.E_English.Contains("O") || item.E_English.Contains("Ｏ"))
                {
                    totalE_English += 1;
                }

                #region 08/13/2010 增加中国语权限 和 英数日语A权限 对应统计信息。
                //A Japan
                if (item.A_Japan.Contains("O") || item.A_Japan.Contains("Ｏ"))
                {
                    totalA_Japan += 1;
                }
                //A English
                if (item.AB_English.Contains("O") || item.AB_English.Contains("Ｏ"))
                {
                    totalA_English += 1;
                }

                //A Chinese
                if (item.A_Chinese.Contains("O") || item.A_Chinese.Contains("Ｏ"))
                {
                    totalA_Chinese += 1;
                }

                //AB_Chinese
                if (item.AB_Chinese.Contains("O") || item.AB_Chinese.Contains("Ｏ"))
                {
                    totalAB_Chinese += 1;
                }

                //D_Chinese
                if (item.D_Chinese.Contains("O") || item.D_Chinese.Contains("Ｏ"))
                {
                    totalD_Chinese += 1;
                }

                //E_Chinese
                if (item.E_Chinese.Contains("O") || item.E_Chinese.Contains("Ｏ"))
                {
                    totalE_Chinese += 1;
                }

                #endregion 08/13/2010 增加中国语权限 和 英数日语A权限 对应统计信息。

                #region 12/24/2010 增加 F和G 对应统计信息

                //F_Japan
                if (item.F_Japan.Contains("O") || item.F_Japan.Contains("Ｏ"))
                {
                    totalF_Japan += 1;
                }
                //G_Japan
                if (item.G_Japan.Contains("O") || item.G_Japan.Contains("Ｏ"))
                {
                    totalG_Japan += 1;
                }

                //F_English
                if (item.F_English.Contains("O") || item.F_English.Contains("Ｏ"))
                {
                    totalF_English += 1;
                }
                //G_English
                if (item.G_English.Contains("O") || item.G_English.Contains("Ｏ"))
                {
                    totalG_English += 1;
                }
                //F_Chinese
                if (item.F_Chinese.Contains("O") || item.F_Chinese.Contains("Ｏ"))
                {
                    totalF_Chinese += 1;
                }
                //G_Chinese
                if (item.G_Chinese.Contains("O") || item.G_Chinese.Contains("Ｏ"))
                {
                    totalG_Chinese += 1;
                }
                #endregion 12/24/2010 增加 F和G 对应统计信息

            }

            totalPersons = eResult.Count;

           
            #endregion 统计 所有权限中O的数量
        }

        #endregion 统计权限数据

        #endregion 查询相关

        #region BusyBar
        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busy秒数 busysecond</param>
        public void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);

            DataContext = true;

            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000);
            });
        }
        #endregion BusyBar

        #region 清空或是设置 统计 变量和控件的值
        /// <summary>
        /// 清空或是设置 统计 变量和控件的值
        /// </summary>
        /// <param name="isClear">当为TRUE时，Value值设置有效。当为FALSE时，统计值为当前值</param>
        /// <param name="value">The value.</param>
        /// <value>08/13/2010 增加中国语权限 和 英数日语A权限 对应统计信息。</value>
        void ClearOrSetTotalValue(bool isClear, int value)
        {
            //当为TRUE时，Value值设置有效
            if (isClear == true)
            {
                totalPersons = value;
                totalDistinguish = value;
                totalTrimer = value;

                totalAB_Japan = value;
                totalD_Japan = value;
                totalE_Japan = value;

                totalAB_English = value;
                totalD_English = value;
                totalE_English = value;

                #region 08/13/2010 add
                totalA_English = value;
                totalA_Japan = value;
                totalA_Chinese = value;
                totalAB_Chinese = value;
                totalD_Chinese = value;
                totalE_Chinese = value;
                #endregion 08/13/2010 add

                #region 12/24/2010 add
                totalF_Chinese = value;
                totalF_English = value;
                totalF_Japan = value;
                totalG_Chinese = value;
                totalG_English = value;
                totalG_Japan = value;
                #endregion 12/24/2010 add

            }

            this.tbPersons.Text = string.Empty;
            this.tbDistinguish.Text = string.Empty;
            this.tbTrimer.Text = string.Empty;

            this.tbAB_Japan.Text = string.Empty;
            this.tbD_Japan.Text = string.Empty;
            this.tbE_Japan.Text = string.Empty;

            this.tbAB_English.Text = string.Empty;
            this.tbD_English.Text = string.Empty;
            this.tbE_English.Text = string.Empty;

            #region 08/13/2010 --add
            this.tbA_English.Text = string.Empty;
            this.tbA_Japan.Text = string.Empty;
            this.tbA_Chinese.Text = string.Empty;
            this.tbAB_Chinese.Text = string.Empty;
            this.tbD_Chinese.Text = string.Empty;
            this.tbE_Chinese.Text = string.Empty;
            #endregion 08/13/2010 --endadd

            #region 12/24/2010 --add
            this.tbF_Chinese.Text = string.Empty;
            this.tbF_English.Text = string.Empty;
            this.tbF_Japan.Text = string.Empty;
            this.tbG_Chinese.Text = string.Empty;
            this.tbG_English.Text = string.Empty;
            this.tbG_Japan.Text = string.Empty;
            #endregion 12/24/2010 --endadd

            this.tbPersons.Text = "共 " + totalPersons.ToString() + " 人";
            this.tbDistinguish.Text = "仕分：" + totalDistinguish.ToString() + " 人";
            this.tbTrimer.Text = "トリマ：" + totalTrimer.ToString() + " 人";

            this.tbAB_Japan.Text = "日本語AB：" + totalAB_Japan.ToString() + " 人";
            this.tbD_Japan.Text = "日本語D：" + totalD_Japan.ToString() + " 人";
            this.tbE_Japan.Text = "日本語E：" + totalE_Japan.ToString() + " 人";

            this.tbAB_English.Text = "英数AB：" + totalAB_English.ToString() + " 人";
            this.tbD_English.Text = "英数D：" + totalD_English.ToString() + " 人";
            this.tbE_English.Text = "英数E：" + totalE_English.ToString() + " 人";

            #region 08/13/2010 --add
            this.tbA_English.Text = "英数A：" + totalA_English.ToString() + " 人";
            this.tbA_Japan.Text = "日本語A：" + totalA_Japan.ToString() + " 人";
            this.tbA_Chinese.Text = "中国語A：" + totalA_Chinese.ToString() + " 人";
            this.tbAB_Chinese.Text = "中国語AB：" + totalAB_Chinese.ToString() + " 人";
            this.tbD_Chinese.Text = "中国語D：" + totalD_Chinese.ToString() + " 人";
            this.tbE_Chinese.Text = "中国語E：" + totalE_Chinese.ToString() + " 人";
            #endregion 08/13/2010 --endadd

            #region 12/24/2010 --add
            this.tbF_Chinese.Text = "中国語F：" + totalF_Chinese.ToString() + " 人";
            this.tbF_English.Text = "英数F：" + totalF_English.ToString() + " 人";
            this.tbF_Japan.Text = "日本語F：" + totalF_Japan.ToString() + " 人";
            this.tbG_Chinese.Text = "中国語G：" + totalG_Chinese.ToString() + " 人";
            this.tbG_English.Text = "英数G：" + totalG_English.ToString() + " 人";
            this.tbG_Japan.Text = "日本語G：" + totalG_Japan.ToString() + " 人";
            #endregion 12/24/2010 --endadd

        }
        #endregion 清空或是设置 统计 变量和控件的值

        #region 数据导出
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        void btnExport_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.dgOPRolesDataListExport.ItemsSource == null)
                {
                    throw (new Exception("请查询后再将数据导出。"));
                }
                else
                {
                    //记录导出前分页数，导出后还原。
                    //让导出的数据每页记录数为所有记录总数，导出数据为排序后的结果
                    this.oldNumericUpDown = this.nuPageSize.Value;
                    this.pcv.PageSize = this.sumRecordCount;
                    this.DataToCSV.ItemsSource = this.pcv;

                    //dgOPRolesDataExport 取表头的数据源
                    ExportDataToFile(this.dgOPRolesDataListExport);
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                ctrlName + 
                                                ex.Message.ToString() +
                                                this.whereInforLogs);

                Common.FunctionList.FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="grid"></param>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = Orid.Management.Statistics.OperatorUnitMangement.Common.Export.DataExport.ExportDataGrid(true, grid, DataToCSV, null);
                    
                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {

                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }
                        stream.Close();
                    }

                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);

                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    " 在 " + this.ctrlName + " 中导出记录" +
                                                    this.whereInforLogs);

                    Common.FunctionList.FunctionClass.ShowMessageBox(
                       this.errorMessbox,
                       0,
                       "提示",
                       "数据已导出。",
                       Colors.Gray,
                       true,
                       Visibility.Visible,
                       Visibility.Collapsed);
                    return;
                }
                else
                {
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    return;
                }
            }
            catch (Exception ex)
            {
                this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr + 
                                                    ctrlName + 
                                                    ex.Message.ToString() +
                                                    this.whereInforLogs);

                Common.FunctionList.FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      1,
                      "提示",
                      ex.Message.ToString(),
                      Colors.Gray,
                      true,
                      Visibility.Visible,
                      Visibility.Collapsed);

                return;
            }

        }
        #endregion 数据导出

        #region 利用DataGrid的LoadingRow 变色
        /// <summary>
        /// 用LoadingRow事件，动态设置内容变色
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The instance containing the event data.</param>
        /// <value>10/12/2010 Add by zhangjun</value>
        void dgOPRolesDataListExport_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            /*
             * 使用DataGridTextColumn，在DataGrid.LoadingRow事件中，
             * 利用DataGridTextColumn.GetCellContent(DataGridRowEventArgs.Row)的方式取出儲存格中
             * 的視覺元素(對DataGridTextColumn而言，就是TextBlock)，將其轉型為TextBlock，
             * DataGridRowEventArgs.Row.DataContext可取得資料物件，用Reflection的技巧取出想要变化的Binding，
             * 再依其条件調整TextBlock的Foreground屬性。Reflection的地方可以用switch或if配合Hardcoding取代
             * (例如: if (c.Header.ToString() == "A") {str = sd.ScoreA;} )，或者可以用Binding + Converter方式
             * 將前景色跟資料屬性值綁在一起
             * */

            SolidColorBrush magenta = new SolidColorBrush(Colors.Magenta);
            SolidColorBrush darkGray = new SolidColorBrush(Colors.DarkGray);
            SolidColorBrush normal = new SolidColorBrush(Colors.Black);

            OperatorRolesData operRoleData = e.Row.DataContext as OperatorRolesData;
            //巡過所有欄位，找出所有要想变化的Binding
            foreach (DataGridColumn column in dgOPRolesDataListExport.Columns)
            {
                //動態取得TextBlock物件
                TextBlock tb = column.GetCellContent(e.Row) as TextBlock;
                //e.Row.DataContext就是OperatorRolesData, 可以Hard-Coding去取operRoleData.A/B
                //這裡則示範用Reflection(反射)法取Binding目標欄位值
                PropertyInfo pi = operRoleData.GetType().GetProperty((column as DataGridTextColumn).Binding.Path.Path);

                string str = Convert.ToString(pi.GetValue(operRoleData, null));

                //如果是0用magenta 不是0是X用darkGray 其它用normal(黑)色
                tb.Foreground = str.ToUpper() == "O" || str == "0" ? magenta : str.ToUpper() == "X" ? darkGray : normal;
            }
        }

        #endregion
    }
}
